package org.example.command;

import org.example.model.HTMLDocument;
import org.example.model.DeletedElementInfo;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class DeleteElementCommand implements CanUndoCommand {

    private final HTMLDocument document;
    private final String elementId;
    private DeletedElementInfo deletedElementInfo;

    private DeleteElementCommand(HTMLDocument document, String elementId) {
        this.document = document;
        this.elementId = elementId;
    }

    public static Command create(HTMLDocument document, String elementId) {
        return new DeleteElementCommand(document, elementId);
    }

    @Override
    public boolean execute() {

        try {
            deletedElementInfo = document.deleteElement(elementId);
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
            return false;
        }

        return true;
    }

    @Override
    public void undo() {
        if (deletedElementInfo != null) {
            Element parentElement = deletedElementInfo.getParentElement();
            Element deletedElement = deletedElementInfo.getDeletedElement();
            int originalIndex = deletedElementInfo.getOriginalIndex();

            // 找到父元素中的所有 Element 子节点
            Elements elementChildren = parentElement.children();

            // 根据索引将被删除的元素插回正确的位置
            if (originalIndex >= elementChildren.size()) {
                parentElement.appendChild(deletedElement);  // 如果索引超出范围，则追加到最后
            } else {
                elementChildren.get(originalIndex).before(deletedElement);  // 插入到指定位置前面
            }
        }
    }


    @Override
    public boolean equals(Object obj) {
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;
        DeleteElementCommand other = (DeleteElementCommand) obj;
        return this.elementId.equals(other.elementId);
    }

    @Override
    public int hashCode() {
        return elementId.hashCode();
    }

    @Override
    public String toString() {
        return "DeleteElementCommand{" + "elementId='" + elementId + "'}";
    }
}
